<?php
// 用户进行对于数据库的操作
namespace App\Models;

use App\Config\Database;
use PDO;
use PDOException;

class User{
    private $conn;
    private $table = 'Users';

    // 用户属性
    public $id;
    public $user_id;
    public $username;
    public $email;
    public $password_hash;
    public $avatar_url;
    public $status;

    public function __construct() {
        //数据库的初始化
        $database = new Database();
        $this->conn = $database->getConnection();
    }

    // 用户注册
    public function register(){
        try {
            $query = "INSERT INTO" .$this->table. "(user_id, username, email, password_hash, avatar_url, status) 
                      VALUES (:user_id, :username, :email, :password_hash, :avatar_url, 1)";
            $stmt = $this->conn->prepare($query);
            // 绑定参数
            $stmt->bindParam(':user_id', $this->user_id);
            $stmt->bindParam(':username', $this->username);
            $stmt->bindParam(':email', $this->email);
            $stmt->bindParam(':password_hash', $this->password_hash);
            $stmt->bindParam(':avatar_url', $this->avatar_url);

            return $stmt->execute();
        } catch(PDOException $e) {
            error_log("Registration error: " .$e->getMessage());
            return false;
        }
    }

    // 通过user_id查找用户
    public function findByUserId($user_id){
        try{
            $query = "SELECT * FROM " . $this->table . " WHERE user_id = :user_id LIMIT 1";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(":user_id", $user_id);
            $stmt->execute();

            return $stmt->fetch(PDO::FETCH_ASSOC);
        }catch(PDOException $e){
            error_log("Find user error: " .$e->getMessage());
            return false;
        }
    }

    public function exists($user_id){
        return $this->findByUserId($user_id) !== null;
    }

    public function existsUserId($user_id){
        $user = $this->findByUserId($user_id);
        // 确保只在查询成功且返回结果时才认为用户存在
        return $user !== false && $user !== null;
    }
    
    // 通过id查找用户
    public function findById($id){
        try{
            $query = "SELECT * FROM " . $this->table . " WHERE id = :id LIMIT 1";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(":id", $id);
            $stmt->execute();

            return $stmt->fetch(PDO::FETCH_ASSOC);
        }catch(PDOException $e){
            error_log("Find user error: " .$e->getMessage());
            return false;
        }
    }
}
?>